package com.ffs.lock;

import java.util.List;
import java.util.concurrent.locks.Lock;

/**
 * 链锁
 *
 * @author ffs80 created 2021/7/2
 */
public class ChainLock {

    private final Lock current;
    private final ChainLock next;

    public ChainLock(List<ObjectLock> locks) {
        if ((locks == null) || (locks.isEmpty())) {
            throw new IllegalArgumentException("锁数量不能为0");
        }
        this.current = locks.remove(0);
        if (locks.size() > 0) {
            this.next = new ChainLock(locks);
        } else {
            this.next = null;
        }
    }

    public void lock() {
        this.current.lock();
        if (this.next != null) {
            this.next.lock();
        }
    }

    public void unLock() {
        if (this.next != null) {
            this.next.unLock();
        }
        this.current.unlock();
    }
}
